package com.dongdong.bookstore.security.components;

import com.dongdong.bookstore.security.model.UserCategory;
import com.dongdong.bookstore.security.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.startup.UserConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <ul>
 *     <li>获得header中token</li>
 *     <li>
 *         校验token合法性
 *     </li>
 *     <li>
 *         token合法则构造
 *         UsernamePasswordAuthenticationToken
 *         并交给SecurityContextHolder
 *     </li>
 * </ul>
 * 注入角色权限信息和登录用户基本信息
 * @author chiangkai
 * @date 2021-09-17
 * @email chiangkk@163.com
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && (authHeader.startsWith(UserCategory.ADMIN.ordinal()+this.tokenHead) ||
                authHeader.startsWith(UserCategory.VIP.ordinal()+this.tokenHead) )) {
            String authToken = authHeader.substring(this.tokenHead.length()+1);// The part after "Bearer "
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            log.info("checking username:{}", username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(authHeader.charAt(0)+username);
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    log.info("authenticated user:{}", username);
                    // 全局注入角色权限信息和登录用户基本信息
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(request, response);

    }
}
